/**
 * AI客户端 - 封装AI服务API调用的核心客户端
 *
 * 开发人员：徐少洋
 * 开发时间：2025-11-08 至 2025-11-12
 * 模块职责：封装AI多模态服务的HTTP API调用，支持图像分析、文档解析等AI功能
 *
 * 技术要点：
 * - 多模态AI API封装和调用
 * - HTTP请求构造和响应解析
 * - 认证头和请求头管理
 * - 异常处理和降级策略
 * - 多模型支持和配置管理
 *
 * 开发故事：负责AI客户端的设计和实现，与AI配置和AI聊天服务深度配合，确保AI功能的稳定性和可靠性。
 */
package com.pbl.ai;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pbl.config.props.AiProps;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AiClient {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final AiProps aiProps;

    /**
     * 构造AI客户端
     * @param aiProps AI服务配置属性
     */
    public AiClient(AiProps aiProps) {
        this.aiProps = aiProps;
    }

    public String analyzeImage(String imageUrl, String prompt) {
        try {
            String url = aiProps.getBaseUrl() + "/chat/completions";

            Map<String, Object> payload = new HashMap<>();
            payload.put("model", aiProps.getModel());
            Map<String, Object> contentImage = new HashMap<>();
            contentImage.put("type", "image_url");
            Map<String, Object> imageUrlMap = new HashMap<>();
            imageUrlMap.put("url", imageUrl);
            imageUrlMap.put("detail", "high");
            contentImage.put("image_url", imageUrlMap);
            Map<String, Object> contentText = new HashMap<>();
            contentText.put("type", "text");
            contentText.put("text", prompt);
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", List.of(contentImage, contentText));
            payload.put("messages", List.of(message));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiProps.getApiKey());

            HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(payload), headers);
            Map resp = restTemplate.postForObject(url, entity, Map.class);
            if (resp == null) return null;
            List choices = (List) resp.get("choices");
            if (choices == null || choices.isEmpty()) return null;
            Map first = (Map) choices.get(0);
            Map msg = (Map) first.get("message");
            Object content = msg.get("content");
            return content == null ? null : content.toString();
        } catch (Exception e) {
            return null;
        }
    }
}


